package com.sui.bigdata.sml.web.service.impl;

import com.sui.bigdata.sml.web.dto.ProjectDTO;
import com.sui.bigdata.sml.web.repository.model.Project;
import com.sui.bigdata.sml.web.service.ProjectService;
import com.sui.bigdata.sml.web.exception.EntityNotFoundException;
import com.sui.bigdata.sml.web.repository.mapper.ExperimentMapper;
import com.sui.bigdata.sml.web.repository.mapper.ProjectMapper;
import com.sui.bigdata.sml.web.util.Constants;
import lombok.extern.slf4j.Slf4j;
import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author songhaicheng
 * @date 2019/11/5 13:49
 * @description
 * @reviewer
 */
@Service
@DependsOn("disconfConfig")
@Slf4j
public class ProjectServiceImpl implements ProjectService {

    @Autowired
    private ProjectMapper mapper;
    @Autowired
    private ExperimentMapper experimentMapper;
    @Autowired
    private MapperFacade mapperFacade;

    @Override
    public Long add(ProjectDTO dto) {
        Project project = mapperFacade.map(dto, Project.class);
        // 给 userId 占位
        project.setUserId(Constants.DEFAULT_USER_ID);
        mapper.insert(project);
        return project.getId();
    }

    @Override
    public ProjectDTO get(Long id) {
        Project project = mapper.get(id);
        if (project == null) {
            throw new EntityNotFoundException(Project.class, id);
        }
        return mapperFacade.map(project, ProjectDTO.class);
    }

    @Override
    public Boolean update(ProjectDTO dto) {
        get(dto.getId());
        Project project = mapperFacade.map(dto, Project.class);
        return mapper.update(project) == 1;
    }

    @Override
    public Boolean delete(Long id) {
        get(id);
        if (mapper.delete(id) == 1) {
            // 找到目标项目下所有没有被标记为删除的实验，标记为删除
            experimentMapper.listByProjectId(id, false).forEach(exp -> {
                try {
                    exp.setDelete(true);
                    experimentMapper.update(exp);
                } catch (Exception e) {
                    log.error("删除实验 【" + exp.getName() + "】失败，跳过该实验", e);
                }
            });
        }
        return true;
    }

    @Override
    public List<ProjectDTO> listAll() {
        return mapperFacade.mapAsList(mapper.listByUserId(null), ProjectDTO.class);
    }

}
